package com.springboot.redis.demo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 网站日常指标统计案例
 *
 * @author: zr
 * @date: 2021-11-17
 */
public class WebsiteStatisticsDemo extends RedisClient {

    /**
     * Redis key
     */
    public static String KEY_PREFIX = "hyperloglog_uv1_";

    /**
     * 初始化uv数据
     *
     * @param date
     * @return
     * @throws
     * @date 2021-11-17
     */
    public static void initUvData(String date) {
        Random random = new Random();
        int startIndex = random.nextInt(1000);
        System.out.println("今日访问起始id为：" + startIndex);
        for (int i = startIndex; i < startIndex + 1358; i++) {
            jedis.pfadd(KEY_PREFIX + date, String.valueOf(i + 1));
        }
    }


    /**
     * 判断内容是否是垃圾内容
     *
     * @param
     * @return
     * @throws
     * @date 2021-11-17
     */
    public static long getUv(String date) {
        return jedis.pfcount(KEY_PREFIX + date);
    }

    /**
     * 获取7天之内的
     *
     * @param
     * @return {@link long}
     * @throws
     * @date 2021-11-17
     */
    public static long getWeeklyUv() {
        List<String> weeks = new ArrayList<>();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());

        for (int i = 0; i < 7; i++) {
            instance.add(Calendar.DAY_OF_YEAR, 1);
            String date = simpleDateFormat.format(instance.getTime());
            weeks.add(KEY_PREFIX + date);
        }

        String[] array = weeks.toArray(new String[weeks.size()]);
        jedis.pfmerge("weekly_uv", array);
        return jedis.pfcount("weekly_uv");
    }

    public static void main(String[] args) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());

        long duplicatUv = 0;

        for (int i = 0; i < 7; i++) {
            instance.add(Calendar.DAY_OF_YEAR, 1);
            String date = simpleDateFormat.format(instance.getTime());
            initUvData(date);

            long uv = getUv(date);

            System.out.println("日期为：" + date + "的uv值为：" + uv);
            duplicatUv += uv;
        }
        System.out.println("未去重的周活跃用户数为：" + duplicatUv);
        long weeklyUv = getWeeklyUv();
        System.out.println("实际的周活跃用户数为：" + weeklyUv);
    }
}
